using System.Security;
using Agatha.Common;

namespace Source.ServiceLayer
{
    public abstract class BusinessRequestHandler<TRequest, TResponse> : NhRequestHandler<TRequest, TResponse>

        where TRequest : Request

        where TResponse : Response, new()
    {

        public IAuthenticator Authenticator { get; set; }

        public IAuthenticationContext AuthenticationContext { get; set; }

        public IAuthorizationProvider AuthorizationProvider { get; set; }


        protected override void DisposeManagedResources()
        {

            AuthorizationProvider = null;

            AuthenticationContext = null;


            base.DisposeManagedResources();

        }



        public override void BeforeHandle(TRequest request)
        {

          //  log4net.MDC.Set("Tenant", ConfigurationProvider.TenantName);

            base.BeforeHandle(request);

            Authenticate(request);

            Authorize(request);

        }



        public virtual void Authorize(TRequest request) { }

        private void Authenticate(TRequest request)
        {

            var emsRequest = request as EmsRequest;

            if (emsRequest != null)
            {

                if (Authenticator.AreValidCredentials(emsRequest.ApplicationUserId, emsRequest.ApplicationUserName, emsRequest.PasswordHash))
                {

                    AuthenticationContext.SetContextData(emsRequest.ApplicationUserId, emsRequest.ApplicationUserName);

                }

                else
                {

                    throw new SecurityException("request could not be authenticated!");

                }

            }

        }

    }

    internal class EmsRequest
    {
        public int ApplicationUserId{ get; set;}
        public string ApplicationUserName { get; set; }
        public string PasswordHash { get; set; }
    }

    public interface IAuthorizationProvider
    {
    }

    public interface IAuthenticationContext
    {
        void SetContextData(object o, object o1);
    }

    public interface IAuthenticator
    {
        bool AreValidCredentials(object o, object o1, object o2);
        bool Authenticate(string name, string hash, UserCredential credential);
    }

    public class UserCredential
    {
    }
}